package com.woniu.zsd.shopping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.zsd.shopping.dao.ProductMapper;
import com.woniu.zsd.shopping.dao.ProductOrderLogMapper;
import com.woniu.zsd.shopping.dto.ProductStatisticsDto;
import com.woniu.zsd.shopping.dto.QueryProductOrderDto;
import com.woniu.zsd.shopping.model.AddReceiverInfoParam;
import com.woniu.zsd.shopping.model.Product;
import com.woniu.zsd.shopping.model.ProductOrder;
import com.woniu.zsd.shopping.dao.ProductOrderMapper;
import com.woniu.zsd.shopping.model.ProductOrderLog;
import com.woniu.zsd.shopping.param.AddProductOrderParam;
import com.woniu.zsd.shopping.service.ProductOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.tomcat.jni.Proc;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.locks.Lock;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangtao
 * @since 2025年02月18日
 */
@Service
public class ProductOrderServiceImpl extends ServiceImpl<ProductOrderMapper, ProductOrder> implements ProductOrderService {
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductOrderMapper productOrderMapper;

    @Resource
    private ProductOrderLogMapper productOrderLogMapper;
    @Override
    public ProductStatisticsDto productStatistics(LocalDateTime startOfDay, LocalDateTime endOfDay) throws Exception {
        ProductStatisticsDto dto= productOrderMapper.productStatistics(startOfDay,endOfDay);
        return dto;
    }

    @Override
    public void addProductOrder(AddProductOrderParam param) throws Exception {
        //创建锁
        RLock lock=redissonClient.getLock(param.getOrderPeople());
        try {
            //加锁
            lock.lock();
            //判断库存是否充足
            QueryWrapper<Product> wrapper=new QueryWrapper<>();
            wrapper.eq("product_id",param.getProductId());
            Product product=productMapper.selectOne(wrapper);
            if(product.getStockNum()<param.getOrderNumber()){
                throw new Exception("库存不足");
            }
            //扣减库存
            product.setStockNum(product.getStockNum()-param.getOrderNumber());
            productMapper.updateById(product);
            //创建订单
            ProductOrder order =new ProductOrder();
            long timestamp = System.currentTimeMillis();
            order.setProductOrderId((int) timestamp);
            order.setProductId(param.getProductId());
            order.setCreatedAt(LocalDateTime.now());
            order.setOrderPeople(param.getOrderPeople());
            order.setStatus(0);
            order.setOrderNumber(param.getOrderNumber());
            order.setAddress(param.getAddress());
            int costPoints = product.getRequiredPoints()*param.getOrderNumber();
            order.setCostPoint(costPoints);
            order.setAddress(param.getAddress());
            order.setReceiverName(param.getReceiverName());
            productOrderMapper.insert(order);
            //插入日志表
            ProductOrderLog productOrderLog = new ProductOrderLog();
            productOrderLog.setProductOrderId((int) timestamp);
            productOrderLog.setOperator(param.getOrderPeople());
            productOrderLog.setOperatedAt(LocalDateTime.now());
            productOrderLog.setType(1);
            productOrderLogMapper.insert(productOrderLog);
        } finally {
            //释放锁
            redissonClient.getLock("product_order_lock").unlock();
        }


    }

    @Override
    public void updateProductOrderStatus(Integer productOrderId, Integer status) throws Exception {
        ProductOrder order=productOrderMapper.selectById(productOrderId);
        if(order==null){
            throw new Exception("订单不存在");
        }
        //创建锁
        RLock lock=redissonClient.getLock(productOrderId.toString());
        try {
            //加锁
            lock.lock();
            order.setStatus(status);
            order.setFinishedAt(LocalDateTime.now());
            productOrderMapper.updateById(order);
            //插入日志表
            ProductOrderLog productOrderLog = new ProductOrderLog();
            productOrderLog.setProductOrderId(productOrderId);
            productOrderLog.setOperator(order.getReceiverName());
            productOrderLog.setOperatedAt(LocalDateTime.now());
            productOrderLog.setType(2);
            productOrderLogMapper.insert(productOrderLog);
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    @Override
    public void addReceiverInfo(AddReceiverInfoParam param) throws Exception {
        ProductOrder order=productOrderMapper.selectById(param.getProductOrderId());
        if(order==null){
            throw new Exception("订单不存在");
        }
        //创建锁
        RLock lock=redissonClient.getLock(param.getProductOrderId().toString());
        try {
            //加锁
            lock.lock();
            order.setReceiverName(param.getReceiverName());
            order.setReceiverPhone(param.getReceiverPhone());
            productOrderMapper.updateById(order);
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    @Override
    public QueryProductOrderDto queryProductOrder(Integer productOrderId) throws Exception {
        ProductOrder order=productOrderMapper.selectById(productOrderId);
        if(order==null){
            throw new Exception("订单不存在");
        }
        QueryProductOrderDto dto=new QueryProductOrderDto();
        BeanUtil.copyProperties(order,dto);
        Product product = productMapper.selectById(order.getProductId());
        BeanUtil.copyProperties(product,dto);
        return dto;
    }


}
